/***********************************
*
* author:huanglei
* mail:code.huanglei@gmail.com
* version:0.2
*
***********************************/

function Tuan(){
    this.LAST_UPDATE_TIME = 1000 * 60 * 5;
    this.API_URL          = 'http://www.atuanzhang.com';
    this.API_URL_GOODS    = this.API_URL+'/atuanzhang_api_goods?city=#city#&page=#page#';
    this.API_URL_CITYS    = this.API_URL+'/atuanzhang_api_citys';
    this.API_URL_GO       = this.API_URL+'/atuanzhang_api_go?url=#url#';
    this.CACHE_KEY_PREFIX = 'at_';
    this.CACHE_KEY_GOODS  = 'goods';
    this.CACHE_KEY_CITY   = 'city';
    this.cache            = new Cache();
}

Tuan.prototype.goods = function(city,page,fnCallback){
    var cacheGoods = this._option(this.CACHE_KEY_GOODS);
	if (cacheGoods){
	    fnCallback(200,cacheGoods);
		return;
	}
	var me = this;
	var url = this.API_URL_GOODS.replace(/#city#/g,city);
	url = url.replace(/#page#/g,page);
	url = encodeURI(url+'&'+new Date().getTime());
	$.get(url,function(data){
		if(data){
		    //this._option(this.CACHE_KEY_GOODS,data.goods);
			fnCallback(200,data.goods);
		} else {
		    fnCallback(500,'data empty');
		}
	},'json');
}

Tuan.prototype.city = function(fnCallback){
	var cacheCity = this._option(this.CACHE_KEY_CITY);
	if (cacheCity){
	    fnCallback(200,cacheCity);
		return;
	}		
	var me = this;
	var url = this.API_URL_CITYS+'?'+new Date().getTime();
	$.get(url,function(data){
		if(data){
		    //this._option(this.CACHE_KEY_CITY,data);
			fnCallback(200,data);
		} else {
		    fnCallback(500,'data empty');
		}
	},'json');
}

Tuan.prototype._option = function(key,value){
    key =+ this.CACHE_KEY_PREFIX;
    if (value){
        this.cache.set(key,value);
    } else {
        varlue = this.cache.get(key);
    }
    return value;
}

Tuan.prototype.clean = function(){
    this.cache.del(this.CACHE_KEY_PREFIX + this.CACHE_KEY_GOODS);
    this.cache.del(this.CACHE_KEY_PREFIX + this.CACHE_KEY_CITY);
}

/***********************************
*
* Cache
*
*
***********************************/

function Cache(){
}


Cache.prototype.add = function(key,value){
	if(localStorage[key] == value) return false;
	localStorage[key] = value;
}

Cache.prototype.del = function(key){
	delete localStorage[key];	
}

Cache.prototype.set = function(key,value){
	localStorage[key] = value;
}

Cache.prototype.get= function(key){
	return localStorage[key];
}


